<template>
  <div class="home">
    <van-nav-bar
      v-show="edit"
      title="我的信息"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <!-- <van-nav-bar class="blue" title="入连人员自主报备" /> -->
    <!-- <img src="../../assets/images/rlzzbb.png" /> -->
    <div id="container" style="width: 1000px; height: 700px"></div>

    <van-form validate-first ref="formDataRef" @submit="onSubmit">
      <van-cell-group inset title="账户基本信息">
        <van-field name="radio" @click="userCheck()" label="用户类型">
          <template #input>
            <van-radio-group
              v-model="addManForm.sysUserBean.userType"
              direction="horizontal"
            >
              <van-radio name="8">学生</van-radio>
              <van-radio name="9">家长</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          v-model="addManForm.sysUserBean.name"
          name="姓名"
          label="姓名"
          placeholder="姓名"
          :rules="rules.name"
        />

        <van-field
          v-model="addManForm.sysUserBean.cardno"
          name="身份证号"
          label="身份证号"
          placeholder="身份证号"
          :rules="rules.cardno"
          maxlength="18"
        />
        <van-field
          v-model="addManForm.sysUserBean.mobile"
          name="手机号码"
          label="手机号码"
          placeholder="手机号码"
          :rules="rules.cardno"
        />

        <van-field
          v-model="addManForm.sysUserBean.password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="rules.password"
        />
        <van-field
          v-model="password"
          type="password"
          name="确认密码"
          label="确认密码"
          placeholder="确认密码"
        />
      </van-cell-group>
      <!-- <van-field
        label="来连方式"
        v-model="formData.trave_mode"
        name="pattern"
        placeholder="请选择来连方式"
        @focus="showTrave = true"
        :rules="[{ required: true, message: '请选择来连方式' }]"
      /> -->
      <van-cell-group
        inset
        title="学生信息"
        v-for="(item, index) in addManForm.userInfoBeanList"
        :model="addManForm"
        :key="index"
      >
        <van-cell value="删除共同居住人" v-show="gtjzrShow">
          <template #right-icon>
            <van-icon
              style="padding-right: 1rem"
              @click="pushResidentList()"
              name="plus"
              class="search-icon"
              >添加</van-icon
            >
            <van-icon
              @click="removeResident(index)"
              name="cross"
              class="search-icon"
              >删除</van-icon
            >
          </template>
        </van-cell>
        <van-field
          v-model="addManForm.userInfoBeanList[index].name"
          name="学生姓名"
          label="学生姓名"
          placeholder="学生姓名"
          :rules="rules.student"
        />
        <van-field
          v-model="addManForm.userInfoBeanList[index].schoolDistrictName"
          name="学校所属区"
          label="学校所属区"
          placeholder="学校所属区"
          :rules="rules.schoolDistrictName"
        />
        <van-field
          v-model="addManForm.userInfoBeanList[index].schoolName"
          name="学校名称"
          label="学校名称"
          placeholder="学校名称"
          :rules="rules.schoolName"
        />

        <van-field
          v-model="addManForm.userInfoBeanList[index].className"
          name="班级"
          label="班级"
          placeholder="班级"
          :rules="rules.className"
        />
        <van-field
          v-model="addManForm.userInfoBeanList[index].addressProvince"
          name="居住地"
          label="居住地"
          placeholder="居住地"
          :rules="rules.addressProvince"
        />
        <van-field
          v-model="addManForm.userInfoBeanList[index].addressInfo"
          name="详细地址"
          label="详细地址"
          placeholder="详细地址"
          :rules="[{ required: true, message: '请填写详细地址' }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <!-- <van-button round block type="primary" native-type="submit"> -->
        <van-button round block type="primary" @click="startTime()">
          开始任务
        </van-button>
        <van-button round block type="primary" @click="downTime()">
          结束任务
        </van-button>
      </div>
    </van-form>
    <!-- 省市区弹出 -->
    <van-popup
      v-model="show"
      closeable
      position="bottom"
      :style="{ height: '100%' }"
    >
      <div class="container">
        <div
          class="item"
          v-for="(item, index) in forArea"
          :key="index"
          @click="checkoutArea(item)"
        >
          {{ item.name || item }}
        </div>
      </div>
    </van-popup>

    <!-- 出行交通方式类型 -->
    <!-- <van-popup v-model="showTrave" round position="bottom">
      <van-picker
        show-toolbar
        :columns="trave_columns"
        @cancel="showTrave = false"
        @confirm="traveConfirm"
      />
    </van-popup> -->

    <!-- 日期 -->
    <van-popup v-model="showDate" round position="bottom">
      <van-datetime-picker
        @confirm="getConfirm"
        @cancel="showDate = false"
        :min-date="minDate"
        type="date"
        title="选择年月日"
      />
    </van-popup>
  </div>
</template>

<script>
import { areaList } from '@vant/area-data'
import area from '@/libs/area.json'
import { helpUserInsert } from '@/api/self/record'
import { Toast, Dialog } from 'vant'
import AMapLoader from '@amap/amap-jsapi-loader'
export default {
  data() {
    return {
      timer: null,
      edit: false,
      gtjzrShow: false,
      showTwoLabel: false,
      checked: false,
      goDlShow: false,
      showArea: false,
      showArea2: false,
      areaList,
      minDate: new Date(1900, 0, 1),
      showDate: false, // 选择生日
      seat_number_label: '',
      range_label: '',
      columns: ['身份证', '护照', '军官证', '港澳通行证'],
      trave_columns: ['飞机', '火车', '轮渡', '自驾', '客运'],
      sexColumns: ['男', '女'],
      show: false,
      forArea: [],
      password: '', // 密码
      addManForm: {
        sysUserBean: {
          cardno: '', // 身份证号
          name: '', // 姓名
          password: '', // 密码
          mobile: '', // 手机号码
          userType: '8' // "用户类型 8学生 9家长",
        },
        userInfoBeanList: [
          // 0学生 1家长
          {
            name: '',
            cardno: '',
            mobile: '',
            sex: '',
            addressProvince: '',
            addressCity: '',
            addressDistrict: '',
            addressInfo: '',
            schoolId: '',
            schoolName: '',
            classId: '',
            className: '',
            remark: '',
            schoolDistrictName: '',
            schoolDistrictId: ''
          }
        ]
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入姓名',
            trigger: ['blur', 'change']
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号',
            trigger: ['blur', 'change']
          }
        ],
        cardno: [
          {
            required: true,
            message: '请输入身份证号',
            trigger: ['blur', 'change']
          }
        ],
        student: [
          {
            required: true,
            message: '请输入学生姓名',
            trigger: ['blur', 'change']
          }
        ],
        schoolDistrictName: [
          {
            required: true,
            message: '请选择学校区',
            trigger: ['blur', 'change']
          }
        ],
        schoolName: [
          {
            required: true,
            message: '请选择学校名称',
            trigger: ['blur', 'change']
          }
        ],
        className: [
          {
            required: true,
            message: '请选择班级',
            trigger: ['blur', 'change']
          }
        ],
        addressProvince: [
          {
            required: true,
            message: '请选择居住地',
            trigger: ['blur', 'change']
          }
        ],
        addressInfo: [
          {
            required: true,
            message: '请选详细地址',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  mounted() {
    if (this.$route.query.type == 'edit') {
      this.edit = true
    }

    // this.traveConfirm(null)
    // this.formData.code = this.$route.query.code
  },
  created() {
    this.initMap()
  },
  methods: {
    initMap() {
      AMapLoader.load({
        key: 'fffcb8dbeadd51ffb4ca874db1c77435', // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Geocoder', 'AMap.Geolocation'] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then(AMap => {
          var map = new AMap.Map('container', {
            zoom: 15,
            resizeEnable: true
          })
          map.plugin('AMap.Geolocation', () => {
            var geolocation = new AMap.Geolocation({
              enableHighAccuracy: true, // 是否使用高精度定位，默认:true
              timeout: 100, // 超过10秒后停止定位，默认：无穷大
              maximumAge: 0, // 定位结果缓存0毫秒，默认：0
              convert: true, // 自动偏移坐标，偏移后的坐标为高德坐标，默认：true
              showButton: true, // 显示定位按钮，默认：true
              buttonPosition: 'RB', // 定位按钮停靠位置，默认：'LB'，左下角
              buttonOffset: new AMap.Pixel(10, 20),
              showMarker: true, // 定位成功后在定位到的位置显示点标记，默认：true
              showCircle: true, // 定位成功后用圆圈表示定位精度范围，默认：true
              panToLocation: true, // 定位成功后将定位到的位置作为地图中心点，默认：true
              zoomToAccuracy: true // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            })
            map.addControl(geolocation)
            // 获取定位信息
            geolocation.getCurrentPosition((status, result) => {
              console.log('status=====', status)
              console.log('result=====', result)
              if (status == 'complete') {
                // 成功执行的回调函数
                this.onComplete(result)
              } else {
                // 失败执行的回调函数
                this.onError(result)
              }
            })
          })
        })
        .catch(e => {
          console.log(e)
        })
    },
    onComplete(data) {
      console.log('定位成功')
      console.log('经度======', data.position.lng)
      console.log('纬度======', data.position.lat)

      // 发送请求
      // uni.request({
      // 	url: 'https://restapi.amap.com/v3/geocode/regeo', //逆地理编码接口地址。
      // 	data: {
      // 		key: '申请好的Web服务开发者Key',
      // 		//location：经纬度  lng ：经度  lat：纬度
      // 		location: data.position.lng + ',' + data.position.lat,
      // 		radius: 1000,
      // 		extensions: 'all',
      // 		batch: false,
      // 		roadlevel: 0
      // 	},
      // 	header: {
      // 		//自定义请求头信息
      // 	},
      // 	success: (res) => {
      // 	//详细地址信息
      // 		console.log(res.data.regeocode.formatted_address);
      // 	}
      // });
    },
    // 解析定位错误信息
    onError(data) {
      console.log('定位失败')
      console.log('失败原因排查信息:' + data.message)
      console.log('浏览器返回信息:' + data.originMessage)
    },
    startTime() {
      this.timer = window.setInterval(() => {
        setTimeout(() => {
          /// 调取接口
          // axios.request('/api/uc/qmc/hsMobileService/getSSTSign',{"id":"1"} ).then(r => {
          //   // Toast.clear()
          //   const result = r.data.data // 返回数据
          //   console.log(result.data, 'result111111')
          //   delete r.data.url // 删除返回数据中的url字段
          //   Vue.prototype.$hdsdk = new HDSDK(result.data) // 构造sdk实例，并挂载到vue原型
          //   // 也可以不挂载到vue原型，看项目实际需求
          // })
          console.log('timer=========', this.timer)
          console.log('Time==========' + new Date())
        }, 0)
      }, 5000) // 30000
    },
    downTime() {
      console.log('downtime=====', this.timer)
      window.clearInterval(this.timer)
      console.log('downTime==========', window.clearInterval(this.timer))
    },
    pushResidentList() {
      this.addManForm.userInfoBeanList.push({
        // user_info_id: this.$route.query.id,
        name: '',
        cardno: '',
        mobile: '',
        sex: '',
        addressProvince: '',
        addressCity: '',
        addressDistrict: '',
        addressInfo: '',
        schoolId: '',
        schoolName: '',
        classId: '',
        className: '',
        remark: '',
        schoolDistrictName: '',
        schoolDistrictId: ''
      })
    },
    removeResident(index) {
      if (index == 0) {
        Toast.fail('不能继续删除')
        return
      }
      this.addManForm.userInfoBeanList.splice(index, 1)
    },
    userCheck() {
      // this.addManForm.sysUserBean.userType = this.addManForm.addManForm.sysUserBean.userType
      if (this.addManForm.sysUserBean.userType == '8') {
        this.gtjzrShow = false
      } else if (this.addManForm.sysUserBean.userType == '9') {
        this.gtjzrShow = true
      }
    },
    delImg(index) {
      // 删除指定下标的图片对象
      if (isNaN(index) || index >= this.postData.length) {
        return false
      }
      let tmp = []
      for (let i = 0, len = this.postData.length; i < len; i++) {
        if (this.postData[i] !== this.postData[index]) {
          tmp.push(this.postData[i])
        }
      }
      this.postData = tmp
    },
    onRead(file) {
      // 上传图片到图片服务器
      // this.$refs.clothImg.src = file.content
      this.postData.push(file) // postData是一个数组
      // let url = API + '/upload?type=99'
      // let fd = new FormData()
      // fd.append('upImgs', file.file)
      // this.axios.post(url, fd, {headers: {
      //   'Content-Type': 'multipart/form-data'
      // }}).then(res => {
      //   this.imgUrlListValue.push(res.data.urls[0].image) //这里上传到指定的图片服务器，成功后会返回图片的url
      // }).catch(err => {
      //   alert(err)
      // })
    },
    getConfirm(value) {
      let yy = new Date(value).getFullYear()
      let mm = new Date(value).getMonth() + 1
      let dd = new Date(value).getDate()
      this.formData.bithday = yy + '-' + mm + '-' + dd
      this.showDate = false
    },
    onAreaConfirm(value) {
      this.showArea = false
      this.formData.start_addr_list = value
        .filter(item => !!item)
        .map(item => item.name)
        .join('/')
    },
    enAreaConfirm(value) {
      this.showArea2 = false
      this.formData.end_addr_list = value
        .filter(item => !!item)
        .map(item => item.name)
        .join('/')
    },

    goDlConfirm(value) {
      const formatDate = value =>
        `${value.get}/${value.getMonth() + 1}/${value.getDate()}`
      let yy = new Date(value).getFullYear()
      let mm = new Date(value).getMonth() + 1
      let dd = new Date(value).getDate()
      this.formData.estimated_arrival_date = yy + '-' + mm + '-' + dd
      this.goDlShow = false
    },
    onSexConfirm(value) {
      this.label = value
      this.formData.sex = value
      this.showSex = false
    },

    onSubmit() {
      this.$refs.formDataRef
        .validate()
        .then(() => {
          // 验证通过
          console.log(this.addManForm)
        })
        .catch(() => {
          // 验证失败
          // Toast.fail(res.data.msg)
          Toast.fail('验证失败')
        })

      // formdata.sex = this.formData.sex=='男'?1:0

      // Toast.loading({
      //   message: '加载中...',
      //   forbidClick: true,
      //   duration: 10000,
      // })
      // helpUserInsert(formdata).then((res) => {
      //   Toast.clear()
      //   if (res.data.errcode === 0) {
      //     let id =
      //       this.$route.query.id != null
      //         ? this.$route.query.id
      //         : res.data.data.id
      //     this.$router.push({ name: 'recordQrCode', query: { id: id } })
      //     Dialog.alert({
      //       message: '提交成功',
      //       showCancelButton: false,
      //       showConfirmButton: false,
      //     }).then(() => {})
      //     const TIMEOUT = setTimeout(() => {
      //       Dialog.close()
      //       clearTimeout(TIMEOUT)
      //     }, 2000)
      //     // 提交成功清空数据
      //     for (let i in this.formData) {
      //       this.formData[i] = ''
      //       this.formData.avenue_flow_area = true
      //     }
      //   } else {
      //     Toast.fail(res.data.msg)
      //   }
      // })
    }
  }
}
</script>
<style lang="less" scoped>
.upload-img-5 {
  margin: 5px 0 90px 0;
}
.upload-img-1 {
  margin: 5px 0 15px 0;
}

.home {
  height: 100%;
  // background: url('../../assets/images/smtb.jpg') no-repeat;

  img {
    // background: url('../../assets/images/smtb.jpg');
    width: 100%;
  }
  .dialog-container {
    height: 70vh;
    overflow-y: auto;
  }
  .get-area {
    width: 100%;
    padding: 0 0.8rem;
    font-size: 0.747rem;
    color: #fff;
    background-color: #1989fa;
    border: 0.053rem solid #1989fa;
    height: 2.347rem;
    line-height: 2.347rem;
    text-align: center;
    border-radius: 0.107rem;
    cursor: pointer;
    box-sizing: border-box;
    margin-right: 10px;
  }
  /deep/.van-field__label {
    width: 8em;
  }
  /deep/.van-field__error-message {
    text-align: right;
  }
  .title {
    // font-size: 28px;
    text-indent: 20px;
    padding: 50px 0 20px;
  }
  .container {
    width: 90%;
    height: 80vh;
    overflow-y: auto;
    border: 1px solid #adadad;
    margin: auto;
    .item {
      margin: 10px;
    }
  }
}
.up-and-down {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f1f3f4;
  height: 80px;
  color: #333;
}
.home .blue {
  background-color: transparent;
}
.home .van-cell {
  background-color: transparent;
}
</style>
